<?php
/**
 *
 *微信统一下单接口
 *
 *

 * Created by 上海风车教育科技有限公司.
 * User: 刘红伟
 * Date: 15-12-9
 * Email: 454303753@qq.com
 * File:wx_jsapi_unifiedorder.php
 */

class wx_jsapi_unifiedorder {

     private  $total_fee;
     private $openId;
     private  $order_id;
     private  $nonce_str;
     private  $order_no;
     private  $url='https://api.mch.weixin.qq.com/pay/unifiedorder';
    public function __construct($order_id,$openId,$total_fee){
        $this->openId=$openId;
        $this->total_fee=$total_fee;
        $this->order_id=$order_id;
        $this->nonce_str=$this->set_nonce_str();
        $this->order_no=$this->set_order_no();

    }

    private  function get_total_fee(){
       return $this->total_fee*100;
    }
    private function set_nonce_str(){
        return md5(time().'wxcf2296ea434d481b'.'1289649501');
    }
    private  function set_order_no (){
        return date('Ymdhis',time()).'_'.$this->order_id;
    }


    private  function get_sign(){
        $str="appid=".Yii::app()->params['APPID']."&body=".Yii::app()->params['pay_product_info']."&mch_id=".Yii::app()->params['mch_id']."&nonce_str=".$this->nonce_str."&notify_url=".Yii::app()->params['notify_url']."&openid=".$this->openId."&out_trade_no=".$this->order_no."&spbill_create_ip=".$_SERVER['REMOTE_ADDR']."&total_fee=".$this->get_total_fee()."&trade_type=JSAPI&key=".Yii::app()->params['weixin_key'];
       return strtoupper(md5($str));
    }

  private  function get_xml(){
      $xml="<xml>
            <appid>".Yii::app()->params['APPID']."</appid>
            <body>".Yii::app()->params['pay_product_info']."</body>
            <mch_id>".Yii::app()->params['mch_id']."</mch_id>
            <nonce_str>".$this->nonce_str."</nonce_str>
            <notify_url>".Yii::app()->params['notify_url']."</notify_url>
            <openid>".$this->openId."</openid>
            <out_trade_no>".$this->order_no."</out_trade_no>
            <spbill_create_ip>".$_SERVER['REMOTE_ADDR']."</spbill_create_ip>
            <total_fee>".$this->get_total_fee()."</total_fee>
            <trade_type>JSAPI</trade_type>
            <sign>".$this->get_sign()."</sign>
        </xml>";
      return $xml;
  }
    public function create(){
        $http 	= wx_http::factory($this->url, wx_http::TYPE_CURL);
        $result 	= $http->post($this->url, $this->get_xml(), array(
            'Content-type: text/xml'
        ));
        libxml_disable_entity_loader(TRUE);
        return simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
    }

}